<template>
<!-- 联想建议 -->
  <div>
    <van-cell v-for=" (item ,index) in SuggestionList" :key="index"  icon="search"  @click="onsearch(item)">
        <div slot="title" v-html="highLighText(item)"></div>
    </van-cell>
    <!-- 实现高亮
    把搜索关键字用带有行内样式的标签包裹,用v-html进行渲染 -->
  </div>
</template>

<script>
import { getSearchSuggstions } from '@/api/search'
import { debounce } from 'lodash'
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      SuggestionList: []
    }
  },
  name: 'suggestionIndex',
  watch: {
    searchText: {
    // 首次监视触发
      immediate: true,
      handler: debounce(function (val) {
        this.locagetSuggestionIndex(val)
      }, 300)
    }
  },
  methods: {

    async locagetSuggestionIndex (q) {
      try {
        const { data } = await getSearchSuggstions(q)
        this.SuggestionList = data.data.options
        // console.log(this.SuggestionList)
      } catch (err) {
        this.$toast('请求数据失败')
        console.log(err)
      }
    },
    // 推荐关键字高亮
    highLighText (text) {
      // reg 正则,定义要替换的字符
      const reg = new RegExp(this.searchText, 'gi')
      return text?.replace(reg, `<span style="color:red"> ${this.searchText} </sapn>`)
    },
    // 点击搜索
    onsearch (item) {
      this.$emit('search', item)
    }
  }

}
</script>

<style>

</style>
